package com.sys.web.head.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.sys.common.pojo.ApiResponse;
import com.sys.common.pojo.ApiResponseEnum;
import com.sys.common.servlet.BaseServlet;
import com.sys.common.util.ConstatFinalUtil;
import com.sys.users.pojo.TCart;
import com.sys.users.pojo.TCartEnum;
import com.sys.users.pojo.TUsers;
import com.sys.users.pojo.TUsersEnum;
import com.sys.users.service.IUsersDbService;
import com.sys.users.service.impl.UsersDbServiceImpl;

/**
 * 用户首页操作
 * 
 * @author 杨志超
 */
@WebServlet(urlPatterns = "/head/UsersHeadServlet")
public class UsersHeadServlet extends BaseServlet
{
	private IUsersDbService usersDbService;
	
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		this.usersDbService = new UsersDbServiceImpl();
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 接收参数 */
		String method = request.getParameter("method");
		if ("main".equalsIgnoreCase(method))
		{
			/* main */
			main(request, response);
		} else if ("usersUpdateSubmit".equalsIgnoreCase(method))
		{
			/* usersUpdateSubmit */
			usersUpdateSubmit(request, response);
		}else if ("cartList".equalsIgnoreCase(method))
		{
			/* cartList */
			cartList(request, response);
		} else if ("cartInsertSubmit".equalsIgnoreCase(method))
		{
			/* cartInsertSubmit */
			cartInsertSubmit(request, response);
		}else if ("cartDelete".equalsIgnoreCase(method))
		{
			/* cartDelete */
			cartDelete(request, response);
		} else if ("logout".equalsIgnoreCase(method))
		{
			/* logout */
			logout(request, response);
		}
	}
	
	/**
	 * 首页
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void main(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/head/users/main";
		/* 准备路径 */
		/* 从session中获取信息 */
		TUsers users = (TUsers) this.findObjfromSession(request, "users");
		int usersId = users.getId() ;
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", usersId);
		ApiResponse<TUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
		
		String updateFlag = (String) request.getAttribute("updateFlag");
		if(updateFlag == null || "".equalsIgnoreCase(updateFlag))
		{
			/* 清空信息 */
			apiResponse.clearInfo();
		}
		request.setAttribute("response", apiResponse.toJSON());
		/* 根据不同的判断,页面跳转 */
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			/* 修改页面 */
			path = "/head/users/usersUpdate" ; 
		}
		
		path = this.prefix + path + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 更新
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void usersUpdateSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession(); 
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 存储多个结果,Map存储 */
		Map<String, Object> dataMapJava = new HashMap<String, Object>();
		apiResponse.setDataMapJava(dataMapJava);
		
		/* 从session中获取信息 */
		TUsers users = (TUsers) this.findObjfromSession(request, "users");
		int usersId = users.getId() ;
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", usersId);
		ApiResponse<TUsers> apiResponseRes = this.usersDbService.findOneUsersService(condMap);
		request.setAttribute("response", apiResponseRes.toJSON());
		
		users = apiResponseRes.getDataOneJava() ; 
		
		boolean updateFlag = false ; 
		/* 根据不同的判断,页面跳转 */
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			String email = request.getParameter("email");
			String nickName = request.getParameter("nickName");
			String trueName = request.getParameter("trueName");
			String phone = request.getParameter("phone");
			String sex = request.getParameter("sex");
			
			users.setEmail(email);
			users.setNickName(nickName);
			users.setTrueName(trueName);
			users.setPhone(phone);
			users.setSex(Byte.valueOf(sex));
			
			updateFlag = true ; 
		}
		
		/* 更新 */
		if(updateFlag)
		{
			apiResponse = this.usersDbService.updateOneUsersService(users);
			session.setAttribute("users", users);
		}
		apiResponse.setInfo(
				ConstatFinalUtil.INFO_JSON.getString(apiResponseRes.getCode() + ""),
				Collections.EMPTY_MAP);
		
		request.setAttribute("updateFlag", "true");
		request.setAttribute("response", apiResponseRes.toJSON());
		this.main(request,response) ; 
	}
	
	/**
	 * 购物车列表
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String cartList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		/* 准备路径 */
		TUsers users = (TUsers) this.findObjfromSession(request, "users");
		
		/* 分页信息 */
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 查询我的,查询启用的购物车 */
		condMap.put("usersId", users.getId());
		condMap.put("status", TUsersEnum.STATUS_ENABLE.getStatus());
		condMap.put("extend", "true");
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<TCart> apiResponse = this.usersDbService.findCondListCartService(null, condMap);
		/* 将结果存储到Request中 */
		request.setAttribute("response", apiResponse.toJSON());
		
		/* 页面跳转 */
		return "/head/users/cartList" ; 
	}

	/**
	 * 购物车添加提交
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String cartInsertSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		TUsers users = (TUsers) this.findObjfromSession(request, "users");
		
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 准备路径 */
		try
		{
			/* 需要返回json */
			String goodsId = request.getParameter("goodsId");
			String num = request.getParameter("num");
			
			/* 创建对象 */
			TCart cart = new TCart();
			
			/* 赋值 */
			cart.setUsersId(users.getId());
			cart.setGoodsId(Integer.valueOf(goodsId));
			cart.setNum(Integer.valueOf(num));
			cart.setStatus(TCartEnum.STATUS_ENABLE.getStatus());
			cart.setPubTime(new Date());
			
			/* 保存数据库 */
			apiResponse = this.usersDbService.saveOneCartService(cart);
			request.setAttribute("response", apiResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加购物车报错了;",e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 成功,提示 */
		JSONObject resultJSON = apiResponse.toJSON();
		return resultJSON.toJSONString() ; 
	}

	/**
	 * 购物车更新提交
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public String cartDelete(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		/* 按照id查询 */
		String id = request.getParameter("id");
		condMap.put("id", id);
		ApiResponse<TCart> apiResponse = this.usersDbService.findOneCartService(condMap);
		request.setAttribute("response", apiResponse.toJSON());
		
		TCart cart = apiResponse.getDataOneJava() ;
		/* 清空数量 */
		cart.setNum(0);
		cart.setStatus(TCartEnum.STATUS_DISABLED.getStatus());
		
		ApiResponse<Object> apiResponseDb = this.usersDbService.updateOneCartService(cart);
		
		/* 成功,提示 */
		JSONObject resultJSON = apiResponseDb.toJSON();
		return "redirect:/head/users/cartList.htm" ;
	}
	
	/**
	 * 退出
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====logout=====");
		/* 从session中移除数据 */
		HttpSession session = request.getSession() ;
		session.removeAttribute("users");
		/* 客户端跳转 */
		response.sendRedirect(request.getContextPath() + "/NoLoginServlet?method=login");
	}
}
